<template>
  <el-dialog
    :title="'Edit Working Hours'"
    :visible.sync="editDialog"
    :append-to-body="true"
    width="70%"
    :before-close="handleClose">
    <div class="xlSeeFrom">
      <div class="time">
        <div class="time-tit">
          <div class="item">
            <div class="title">Project</div>
          </div>
          <div class="item">
            <div class="item">
              <el-button type="primary" @click.prevent="addRow()">add project</el-button>
              <el-button type="primary" @click.prevent="delData()">delete projects selected</el-button>
            </div>
          </div>
        </div>

        <div class="time-flex">
          <el-table
            :header-cell-style="{background:'#F2F6FC',color:'#606266'}"
            :data="tableData"
            ref="tableData"
            height="335px"
            tooltip-effect="dark"
            border
            stripe
            :row-class-name="rowClassName"
            style="width:100%"
            @selection-change='selectRow'>
            <el-table-column type="selection" width="45" align="center"></el-table-column>
            <el-table-column label="S/N" type="index" width="60" align="center"></el-table-column>
            <el-table-column label="Project" align="center">
              <template slot-scope="scope">
                <el-select
                v-model="scope.row.project_name"
                placeholder="please select"
                style="width:100%"
                @change="(e)=>(selectProject(e,scope.row.xh))">
                    <el-option
                      v-for="item in projectList"
                      :key="item.project_id"
                      :value="item.project_name"
                      :label="item.project_name">
                    </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="Working Hours" align="center">
              <template slot-scope="scope">
                <el-input
                type="number"
                v-model="scope.row.work_hour"
                placeholder="please enter"
                :min="0"
                autocomplete="off"
                @change="onWorkHourInputBlur()">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="Amount" align="center">
              <template slot-scope="scope">{{scope.row.amount}}</template>
            </el-table-column>
          </el-table>
        </div>

      </div>

    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">Close</el-button>
      <el-button  type="success" @click="sure">Confirm</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getProjectAddedList } from '@/request/api'
import { seeWorkingHours,deleteWorkingHours,submitWorkingHours} from '@/request/other_api'
export default {
  data(){
    return {
      editDialog:false,
      //已经添加进系统中的项目（用于选择项目）
      projectList:[],
      //选中要被删除的项目工时
      selectlistRow:[],
      //分配项目工时表的数据
      tableData:[],
      //工资金额
      salary:Number,
      //用户名
      pe_username:'',
      //工资单编号
      salary_id:'',
      //已经选择的项目
      selectedProjedts:[]
    }
  },
  methods:{
    formatData(form,data){
      this.salary = data.salary_money
      this.pe_username = data.pe_username
      this.salary_id = form.salary_id

      getProjectAddedList().then(res => {
        this.projectList = res.data
      })

      //获取分配项目工时详情(保存或提交后查看详情)
      seeWorkingHours({
        pe_username:data.pe_username,
        salary_id:form.salary_id,
        salary_money:data.salary_money
      }).then(res => {
        this.tableData = res.data.projects
        this.tableData.forEach(item => {
          this.selectedProjedts.push({'project_name':item.project_name})
        })
      })

      this.tableData.forEach(item => {
        this.selectedProjedts.push({'project_name':item.project_name})
      })
    },
    //序号
    rowClassName({ row, rowIndex }) {
      row.xh = rowIndex + 1;
    },
    selectRow (val) {
      this.selectlistRow = val
    },
    // 增加项目分配工时记录
    addRow () {
      if(this.tableData.length < 4){
        var list = {
          project_name: '',
          work_hour:0,
          amount:''
        }
        this.tableData.push(list)
      }else {
        this.$message.error('Limit reached!')
      }
    },
    //选择项目
    selectProject(value,xh){
      for(let i = 0;i<this.selectedProjedts.length;i++){
        if(value == this.selectedProjedts[i].project_name) {
          this.$message.error("Duplicate projects")
          this.tableData[xh-1].project_name = ''
          return
        }
      }
      this.selectedProjedts.push({'project_name':value})
    },
    // 删除项目分配工时记录
    delData () {
      for (let i = 0; i < this.selectlistRow.length; i++) {
        let val = this.selectlistRow
        val.forEach((val, index) => {
          this.tableData.forEach((v, i) => {
            if (val.xh === v.xh) {
              this.tableData.splice(i, 1)
            }
          })
        })
        val.forEach((val, index) => {
          this.selectedProjedts.forEach((v, i) => {
            if (val.project_name === v.project_name) {
              this.selectedProjedts.splice(i, 1)
            }
          })
        })
        //调用接口删除库中的记录
        deleteWorkingHours({
          salary_id:this.salary_id,
          pe_username:this.pe_username,
          project_name:this.selectlistRow[i].project_name
        }).then(res =>{
          if(res.code == 200) {
            this.$message.success("Delete Success!")
          }
        })
      }
      this.computeAmount()
    },
    //计算项目金额
    computeAmount(){
      let workHours = 0
      let len = this.tableData.length

      if(len == 1){
        this.tableData[this.tableData.length-1].amount = Number(this.salary).toFixed(2)
      }
      if(len == 2){
        workHours = parseFloat(this.tableData[0].work_hour) + parseFloat(this.tableData[1].work_hour)
        this.tableData[0].amount = ((this.salary / workHours) * parseFloat(this.tableData[0].work_hour)).toFixed(2)
        this.tableData[1].amount = (this.salary - (parseFloat(this.tableData[0].amount)).toFixed(2)).toFixed(2)
      }
      if(len == 3){
        workHours = parseFloat(this.tableData[0].work_hour) + parseFloat(this.tableData[1].work_hour) + parseFloat(this.tableData[2].work_hour)
        this.tableData[0].amount = ((this.salary / workHours) * parseFloat(this.tableData[0].work_hour)).toFixed(2)
        this.tableData[1].amount = ((this.salary / workHours) * parseFloat(this.tableData[1].work_hour)).toFixed(2)
        this.tableData[2].amount = (this.salary - (parseFloat(this.tableData[0].amount) + parseFloat(this.tableData[1].amount)).toFixed(2)).toFixed(2)
      }
      if(len == 4){
        workHours = parseFloat(this.tableData[0].work_hour) + parseFloat(this.tableData[1].work_hour) + parseFloat(this.tableData[2].work_hour) + parseFloat(this.tableData[3].work_hour)
        this.tableData[0].amount = ((this.salary / workHours) * parseFloat(this.tableData[0].work_hour)).toFixed(2)
        this.tableData[1].amount = ((this.salary / workHours) * parseFloat(this.tableData[1].work_hour)).toFixed(2)
        this.tableData[2].amount = ((this.salary / workHours) * parseFloat(this.tableData[2].work_hour)).toFixed(2)
        this.tableData[3].amount = (this.salary - (parseFloat(this.tableData[0].amount)+parseFloat(this.tableData[1].amount)+parseFloat(this.tableData[2].amount))).toFixed(2)
      }
    },
    onWorkHourInputBlur(){
      this.computeAmount()
    },
    // 提交
    sure(){
      for(let i=0;i < this.tableData.length;i++) {
        if(this.tableData[i].project_name == ''){
          this.$message.error("The item cannot be empty!")
          return
        }
        if(this.tableData[i].work_hour == 0) {
          this.$message.error("Working hours cannot be empty!")
          return
        }
      }
      submitWorkingHours({
        salary_id:this.salary_id,
        pe_username:this.pe_username,
        salary_money:this.salary,
        projects:this.tableData
      }).then(res =>{
        if(res.code == 200){
          this.editDialog = false
          this.tableData = []
          this.selectedProjedts = []
          this.$message.success('Success!')
        }else {
          this.$message.error('Error!')
        }
      })
    },
    // 获取选中的数据
    handleClose (done) {
      this.editDialog = false
      this.tableData = []
      this.selectedProjedts = []
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-form-item__label {
  background-color: #eee;
  text-align: center;
  //width: 121px;
}
/deep/ .el-dialog__header {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #eee;
}
/deep/ .el-dialog__body {
  padding: 10px 20px;
  color: #333;
  font-size: 15px;
  word-break: break-all;
}
.tab-item{
  width: 100%;
  padding: 10px 0;
  border: 1px solid #eee;

  table{
    width: 100%;
    font-family: verdana,arial,sans-serif;
    font-size:14px;
    color:#333333;
    border-width: 1px;
    border-color: #999999;
    border-collapse: collapse;
  }
  table td{
    border-width: 1px;
    padding: 4px;
    border-style: solid;
    border-color: #999999;
  }
  table tr td:nth-child(2n+1){
    background-color: #eee;
    width: 13%;
    text-align: center;
  }

  .tab-title{
    font-family: SourceHanSansSC;
    font-weight: 700;
    font-size: 20px;
    color: rgb(16, 16, 16);
    font-style: normal;
    letter-spacing: 0px;
    line-height: 30px;
    text-decoration: none;
    padding: 5px 10px;
    border-bottom: 1px solid #eee;
  }
  /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }

}

.time{
  .time-tit{
    display: flex;
    justify-content: space-between;
    margin: 5px;
    .title{
      font-family: SourceHanSansSC;
      font-weight: 700;
      font-size: 20px;
      color: rgb(16, 16, 16);
      font-style: normal;
      letter-spacing: 0px;
      line-height: 30px;
      text-decoration: none;
    }
  }


  .time-flex{
    display: flex;

    .time-item{
      margin-right: 25px;
    }
    .time-item:last-child{
      margin-right: 0;
    }
  }
}

</style>
